import { Breadcrumb, Button, Form, Input, Select, message, Radio, Upload, Result } from "antd";
import { HomeOutlined, FormOutlined, PlusOutlined } from "@ant-design/icons";
import ReactQuill from "react-quill-new";
import "react-quill-new/dist/quill.snow.css"; // 样式
import "./index.scss";
import http from "@/utils/http";
import { useEffect, useState } from "react";
import useChannel from '@/hooks/useChannel'
import { useSearchParams } from "react-router-dom";

const Publish = () => {
  const [editForm] = Form.useForm();
  // 频道列表
  const { channelList } = useChannel()
  const [channels, setChannels] = useState([]);
  // 定义图片上传类型
  const [imageType, setImageType] = useState(0);
  // 定义上传图片列表
  const [imageList, setImageList] = useState([]);
  // 定义文章是否发布
  const [isPublish, setIsPublish] = useState(false);
  // 获取URL参数
  const [searchParams] = useSearchParams()
  const articleId = searchParams.get('id')

  useEffect(() => {
    function fetchArticleDetail() {
      http.get(`/mp/articles/${articleId}`).then(res => {
        console.log("res-->>>", res);
        // 获取数据
        const { cover, ...formValue } = res.data
        // 设置表单数据
        editForm.setFieldsValue({ ...formValue, type: cover.type })
        // 设置图片数量
        setImageType(cover.type);
        // 显示图片({url:url})
        setImageList(cover.images.map(item => {
          return {
            url: item,
          };
        }));
        // 显示图片({url:url})
        // setImageList(cover.images.map(url => {
        //   return { url }
        // }))
      })
    }
    if (articleId) {
      fetchArticleDetail()
    }
  }, [articleId])

  // 上传图片
  const handleUploadChange = (info) => {
    console.log("Upload change:", info);
    setImageList(info.fileList);
  };
  // 确定发布
  const onFinish = (values) => {
    console.log("Success:", values);
    // 校验图片类型和数量是否吻合
    if (imageType > 0 && imageList.length !== imageType) {
      message.error("请上传正确的图片数量！");
      return;
    }
    const { channel_id, content, title } = values;
    const params = {
      channel_id,
      content,
      title,
      cover: {
        type: imageType,
        // 根据状态处理图片地址
        images: imageList.map((item) => {
          if (item.response) {
            return item.response.data.url; // 处理图片上传地址
          } else {
            return item.url; // 处理图片回显地址
          }
        }),
      },
    };
    if (articleId) {
      // 修改
      http
        .put(`/mp/articles/${articleId}?draft=false`, params)
        .then((res) => {
          console.log(res);
          if (res.message === "OK") {
            message.success("修改成功！");
          } else {
            message.error(res.message || "修改失败！");
          }
        })
        .catch((err) => {
          console.log(err);
        });
    } else {
      // 新增
      http
        .post("/mp/articles?draft=false", params)
        .then((res) => {
          console.log(res);
          if (res.message === "OK") {
            message.success("发布成功！");
            editForm.resetFields();
            setIsPublish(true);
          } else {
            message.error(res.message || "发布失败！");
          }
        })
        .catch((err) => {
          console.log(err);
        });
    }

  };
  const onFinishFailed = (errorInfo) => {
    console.log("Failed:", errorInfo);
  };
  const onReset = () => {
    editForm.resetFields();
  };
  return (
    <div className="publish">
      {/* 面包屑导航 */}
      <Breadcrumb
        items={[
          {
            title: (
              <>
                <HomeOutlined />
                <span>首页</span>
              </>
            ),
          },
          {
            title: (
              <>
                <FormOutlined />
                <span>{articleId ? '编辑文章' : '发布文章'}</span>
              </>
            ),
          },
        ]}
      />
      {!isPublish ? (
        <Form
          name="basic"
          form={editForm}
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          style={{ maxWidth: 1000 }}
          initialValues={{ cover: 0 }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item
            label="标题"
            name="title"
            rules={[{ required: true, message: "请输入标题!" }]}
          >
            <Input placeholder="请输入标题" />
          </Form.Item>

          <Form.Item
            label="频道"
            name="channel_id"
            rules={[{ required: true, message: "请选择一个频道!" }]}
          >
            <Select
              showSearch
              placeholder="请选择频道"
              optionFilterProp="label"
            >
              {channelList.map((item) => (
                <Select.Option key={item.id} value={item.id}>
                  {item.name}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item label="封面" name="cover">
            <div>
              <Form.Item name="type">
                <Radio.Group
                  onChange={(e) => setImageType(e.target.value)}
                >
                  <Radio value={1}> 单图 </Radio>
                  <Radio value={3}> 三图 </Radio>
                  <Radio value={0}> 无图 </Radio>
                </Radio.Group>
              </Form.Item>
              {imageType > 0 && (
                <Upload
                  name="image"
                  listType="picture-card"
                  showUploadList
                  action="http://geek.itheima.net/v1_0/upload"
                  onChange={handleUploadChange}
                  maxCount={imageType}
                  fileList={imageList}
                >
                  <div>
                    <PlusOutlined />
                  </div>
                </Upload>
              )}
            </div>
          </Form.Item>
          <Form.Item label="内容" name="content">
            <ReactQuill
              className="publish-quill"
              theme="snow"
              placeholder="请输入文章内容"
            />
          </Form.Item>

          <Form.Item label={null}>
            <Button
              htmlType="button"
              onClick={onReset}
              style={{ marginRight: 10 }}
            >
              重置
            </Button>
            <Button type="primary" htmlType="submit">
              {articleId ? '编辑文章' : '发布文章'}
            </Button>
          </Form.Item>
        </Form>
      ) : (
        <Result
          status="success"
          title="发布成功"
          subTitle="文章发布成功"
          extra={[
            <Button type="primary" key="console">
              查看文章
            </Button>,
            <Button key="buy" onClick={() => { setIsPublish(false) }}>继续发布</Button>,
          ]}
        />
      )}
    </div>
  );
};
export default Publish;
